package com.erp.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.shop.domain.ErpSellerStoreCookie;
import com.erp.shop.domain.dto.ProductAddActivityDto;
import com.erp.shop.mapper.ErpSellerStorePriceTemplateMapper;
import com.ruoyi.ae.api.RemoteAeActivityService;
import com.erp.shop.mapper.*;
import com.ruoyi.ae.api.RemoteAeActivityService;
import com.ruoyi.gather.api.domain.dto.AutoQueryPriceTemplateInfoDto;
import com.ruoyi.gather.api.domain.dto.SkuInventory;
import com.erp.shop.service.IErpSellerStorePromotionActivityService;
import com.ruoyi.gather.api.RemoteSellerStoreProductService;
import com.ruoyi.gather.api.domain.ErpSellerStoreProduct;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import com.ruoyi.shop.api.domain.ErpSellerStorePromotionActivity;
import com.ruoyi.shop.api.domain.ErpSellerStorePromotionActivityProduct;
import com.ruoyi.shop.api.domain.bo.ErpSellerStorePromotionActivityBo;
import com.ruoyi.shop.api.domain.vo.ErpSellerStorePromotionActivityVo;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 商家促销活动Service业务层处理
 *
 * @author erp
 * @date 2023-06-08
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStorePromotionActivityServiceImpl implements IErpSellerStorePromotionActivityService {
    @Resource
    RestTemplate restTemplate;
    @Resource
    RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    RemoteAeActivityService remoteAeActivityService;
    private final ErpSellerStorePromotionActivityMapper baseMapper;
    private final ErpSellerStoreCookieMapper erpSellerStoreCookieMapper;
    private final ErpSellerStoreEmpowerMapper  erpSellerStoreEmpowerMapper;
    private final ErpSellerStorePriceTemplateMapper erpSellerStorePriceTemplateMapper;
    private final ErpSellerStorePromotionActivityProductMapper erpSellerStorePromotionActivityProductMapper;

    static String path = "http://47.94.131.193:8000";

    /**
     * 查询商家促销活动
     */
    @Override
    public ErpSellerStorePromotionActivityVo queryById(Long activityId) {
        return baseMapper.selectVoById(activityId);
    }

    /**
     * 查询商家促销活动列表
     */
    @Override
    public TableDataInfo<ErpSellerStorePromotionActivityVo> queryPageList(ErpSellerStorePromotionActivityBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpSellerStorePromotionActivity> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStorePromotionActivityVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<ErpSellerStorePromotionActivityVo> activitys = result.getRecords();
        activitys.forEach(activity -> {
            ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectById(activity.getStoreId());
            activity.setStoreName(store.getStoreUserName());
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询商家促销活动列表
     */
    @Override
    public List<ErpSellerStorePromotionActivityVo> queryList(ErpSellerStorePromotionActivityBo bo) {
        LambdaQueryWrapper<ErpSellerStorePromotionActivity> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStorePromotionActivity> buildQueryWrapper(ErpSellerStorePromotionActivityBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStorePromotionActivity> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, ErpSellerStorePromotionActivity::getUserId, bo.getUserId());
        lqw.eq(bo.getStoreId() != null, ErpSellerStorePromotionActivity::getStoreId, bo.getStoreId());
        lqw.like(StringUtils.isNotBlank(bo.getPromotionName()), ErpSellerStorePromotionActivity::getPromotionName, bo.getPromotionName());
        lqw.eq(StringUtils.isNotBlank(bo.getPromotionId()), ErpSellerStorePromotionActivity::getPromotionId, bo.getPromotionId());
        lqw.eq(StringUtils.isNotBlank(bo.getHasPromo()), ErpSellerStorePromotionActivity::getHasPromo, bo.getHasPromo());
        lqw.eq(StringUtils.isNotBlank(bo.getEndTime()), ErpSellerStorePromotionActivity::getEndTime, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getStartTime()), ErpSellerStorePromotionActivity::getStartTime, bo.getStartTime());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ErpSellerStorePromotionActivity::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStorePromotionActivity::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增商家促销活动
     */
    @Override
    public Boolean insertByBo(ErpSellerStorePromotionActivityBo bo) {
        ErpSellerStorePromotionActivity add = BeanUtil.toBean(bo, ErpSellerStorePromotionActivity.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setActivityId(add.getActivityId());
        }
        return flag;
    }

    /**
     * 修改商家促销活动
     */
    @Override
    public Boolean updateByBo(ErpSellerStorePromotionActivityBo bo) {
        ErpSellerStorePromotionActivity update = BeanUtil.toBean(bo, ErpSellerStorePromotionActivity.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStorePromotionActivity entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商家促销活动
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public List<ErpSellerStorePromotionActivity> storeActivityList(Long storeId) {
        List<ErpSellerStorePromotionActivity> activityList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStorePromotionActivity>()
                        .eq(ErpSellerStorePromotionActivity::getStoreId, storeId)
                        .in(ErpSellerStorePromotionActivity::getStatus, "Ongoing", "NotStarted")
                        .orderByDesc(ErpSellerStorePromotionActivity::getStatus)
        );
        activityList.forEach(
                activity -> {
                    String status = null;
                    if (activity.getStatus().equals("Ongoing")) {
                        status = "进行中";
                    } else {
                        status = "未开始";
                    }
                    activity.setPromotionName(activity.getPromotionName() + "  (" + status + ")");
                }
        );


        return activityList;

    }

    @Override
    public R<Object> getPromotionActivityInfo(ErpSellerStorePromotionActivity activity) {
        ErpSellerStorePromotionActivityBo bo = BeanUtil.copyProperties(activity, ErpSellerStorePromotionActivityBo.class);
        ErpSellerStorePromotionActivity activitySel = baseMapper.selectOne(buildQueryWrapper(bo));
        if (Objects.isNull(activity)) {
            return R.ok(null);
        } else {
            return R.ok(activitySel);
        }
    }


    /**
     * 添加商品至活动中
     *
     * @param productId
     * @param activityId
     * @param discount
     * @return
     */
    @Override
    public R<Object> addProductToActivity(Long productId, Long activityId, BigDecimal discount) {

        R<Object> productR = remoteSellerStoreProductService.getSellerStoreProductInfoById(productId.toString());
        String productString = JSONObject.toJSONString(productR.getData());
        ErpSellerStoreProduct product = JSONObject.parseObject(productString, ErpSellerStoreProduct.class);
        if (product == null) {
            return R.fail("未查找到该商品");
        }
        ErpSellerStorePromotionActivity activity = baseMapper.selectOne(new LambdaQueryWrapper<ErpSellerStorePromotionActivity>().eq(ErpSellerStorePromotionActivity::getPromotionId, activityId));
        if (activity == null) {
            return R.fail("未查找到该活动");
        }
        ErpSellerStoreEmpower storeEmpowerPro = erpSellerStoreEmpowerMapper.selectAllById(product.getStoreId());
        ErpSellerStoreEmpower storeEmpowerAct = erpSellerStoreEmpowerMapper.selectAllById(activity.getStoreId());
        if (!storeEmpowerPro.getStoreUserName().equals(storeEmpowerAct.getStoreUserName())) {
            return R.fail("该商品与该活动不在同一店铺中");
        }
        ProductAddActivityDto productDto = new ProductAddActivityDto();
        //放入活动id
        productDto.setPromotion_id(Long.valueOf(activity.getPromotionId()));

        productDto.setStoreId(product.getStoreId().toString());

        //放入折扣信息
        productDto.setExist_store_fans_discount("0");

        //创建商品信息
        List<ProductAddActivityDto.ProductObjects> productObjectList = new ArrayList<>();

        ProductAddActivityDto.ProductObjects productObject = new ProductAddActivityDto.ProductObjects();
        productObject.setProduct_id(product.getAeProductId());

        //活动商品优惠信息
        List<ProductAddActivityDto.ProductDiscountList> productDiscountLists = new ArrayList<>();
        ProductAddActivityDto.ProductDiscountList productDiscount = new ProductAddActivityDto.ProductDiscountList();
        productDiscount.setTerminal("ALL");
        productDiscount.setDiscount(discount.intValue());
        productDiscountLists.add(productDiscount);
        productObject.setProduct_discount_list(productDiscountLists);

        // 商品sku信息
        R<Object> skuAttrR = remoteSellerStoreProductService.getSellerStoreSkuAttr(product.getId());
        String skuAttrString = JSONObject.toJSONString(skuAttrR.getData());
        List<SkuInventory> skuAttrList = JSONArray.parseArray(skuAttrString, SkuInventory.class);

//        List<SkuInventory> skuInventoryLists = new ArrayList<>();
//        SkuInventory skuInventory = new SkuInventory();
        skuAttrList.forEach(sku -> {
            sku.setSku_attr(sku.getSkuAttr());
        });
        productObject.setSku_inventory_list(skuAttrList);

        productObjectList.add(productObject);
        productDto.setProduct_objects(productObjectList);
        String productDtoStr = JSONObject.toJSON(productDto).toString();
//        JSONObject.toJSON(productDto).toString();
        R<Object> activityR = remoteAeActivityService.addProductToActivity(productDtoStr);
        String body = activityR.getData().toString();
        System.out.println(body);
        //判断是否成功
        Integer code = activityR.getCode();

        //插入信息至活动商品表
        ErpSellerStorePromotionActivityProduct activityProduct = new ErpSellerStorePromotionActivityProduct();
        activityProduct.setStoreProductId(product.getId());
        activityProduct.setAeProductId(product.getAeProductId());
        activityProduct.setSkuInventoryList(JSONObject.toJSON(skuAttrList).toString());
        activityProduct.setProductDiscountList(JSONObject.toJSON(productDiscountLists).toString());
        activityProduct.setPromotionId(activity.getPromotionId());
        activityProduct.setActivityId(activityId);
        activityProduct.setStoreClubDiscountRate(String.valueOf(discount.intValue()));
        activityProduct.setExistStoreFansDiscount("0");
        Boolean flag = true;
        if (code == 200) {
            activityProduct.setStatus(1);
        } else {
            flag = false;
            activityProduct.setStatus(0);
        }
        erpSellerStorePromotionActivityProductMapper.insert(activityProduct);

        if (flag) {
            return R.ok("添加活动成功");
        }else {
            return R.fail(body);
        }
    }

    @Override
    public R<Object> processingProjectGroupAndDiscount(AutoQueryPriceTemplateInfoDto templateInfo) {
        Long storeId = templateInfo.getStoreId();
        ErpSellerStoreEmpower store = erpSellerStoreEmpowerMapper.selectById(storeId);
        ErpSellerStorePriceTemplate template = erpSellerStorePriceTemplateMapper.selectById(templateInfo.getTemplateId());
        if (Objects.isNull(template)) {
            return R.fail("定价模版不存在");
        }
        //1、商品折扣
        //2、判断是否是默认
        //设置活动名
        String productDiscountName = null;
        if (Objects.isNull(templateInfo.getProductDiscountId())) {
            Integer isProductDiscount = templateInfo.getIsProductDiscount();
            if (isProductDiscount == 0) {
                //默认
                productDiscountName = template.getDiscount().setScale(0, BigDecimal.ROUND_DOWN).toString();
            } else {
                productDiscountName = templateInfo.getProductDiscount();
            }
            //同步活动
            remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
            //查询这个店铺下的这个活动是否存在，不存在则创建，存在则返回id
            ErpSellerStorePromotionActivity activitySel = baseMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStorePromotionActivity>()
                            .eq(ErpSellerStorePromotionActivity::getStoreId, storeId)
                            .eq(ErpSellerStorePromotionActivity::getPromotionName, productDiscountName)
                            .in(ErpSellerStorePromotionActivity::getStatus, "Ongoing")
                            .last("limit 1")
            );
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 格式化当前时间
            String nowFormatted = now.format(formatter);
            LocalDateTime parse = LocalDateTime.parse(nowFormatted, formatter);
//            LocalDateTime oneDayLater = parse.plusDays(-2);
            LocalDateTime zeroHourOld = parse.plusDays(-1).withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime zeroHour = parse.plusHours(-16);

            //昨天的零点
            System.out.println(zeroHour);

            if (Objects.isNull(activitySel)) {
                //创建活动
                ErpSellerStorePromotionActivity activity = new ErpSellerStorePromotionActivity();
                activity.setUserId(store.getUserId());
                activity.setStoreId(storeId);
                activity.setPromotionName(productDiscountName);

                //开始时间为当前时间-1天
                activity.setStartTime(zeroHour.format(formatter).toString());
                // 原始日期时间
//                String startTime = zeroHour.format(formatter);
                LocalDateTime originalDateTime = LocalDateTime.parse(nowFormatted, formatter);
//                LocalDateTime originalDateTime = LocalDateTime.parse(nowDate);
                // 计算三个月后的日期时间
                LocalDateTime oneMonthLater = originalDateTime.plus(3, ChronoUnit.MONTHS);
                activity.setEndTime(oneMonthLater.format(formatter).toString());

                activity.setErpStatus("0");
                activity.setHasPromo("false");
//                erpSellerStorePromotionActivityMapper.insert(activity);
//                调用接口，上传至平台 //TODO 爬虫相关，暂不执行
                R<Object> activityToAe = createActivityByPython(activity);
                if (activityToAe.getCode() == 200) {
                    //创建成功，拿到对应值
                    //同步活动
                    remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
                } else {
                    activity.setStartTime(zeroHourOld.format(formatter).toString());
                    activityToAe = createActivityByPython(activity);
                    if (activityToAe.getCode() == 200) {
                        remoteAeActivityService.selectStoreOngoingPromotions("1", storeId.toString());
                    }else {
                        return R.fail("活动创建失败");
                    }
                }
            }
            //保存活动id
           ErpSellerStorePromotionActivity activityNew = baseMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerStorePromotionActivity>()
                            .eq(ErpSellerStorePromotionActivity::getStoreId, storeId)
                            .eq(ErpSellerStorePromotionActivity::getPromotionName, productDiscountName)
                            .in(ErpSellerStorePromotionActivity::getStatus, "Ongoing" )
                            .last("limit 1")
            );
            templateInfo.setProductDiscountId(Long.valueOf(activityNew.getPromotionId()));
            templateInfo.setProductDiscount(productDiscountName);
        }

        return R.ok(templateInfo);
    }

    @Override
    public R<Object> insertOrUpdate(ErpSellerStorePromotionActivity activity) {
        if (baseMapper.insertOrUpdate(activity)){
            return R.ok();
        }else {
            return R.fail();
        }
    }


    @Override
    public R<Object> selectActivityInfo(ErpSellerStorePromotionActivity activity) {
        ErpSellerStorePromotionActivityBo bo = BeanUtil.copyProperties(activity, ErpSellerStorePromotionActivityBo.class);
        ErpSellerStorePromotionActivity erpSellerStorePromotionActivity = baseMapper.selectOne(buildQueryWrapper(bo));
        if (Objects.isNull(erpSellerStorePromotionActivity)){
            return R.fail(null);
        }else {
            return R.ok(erpSellerStorePromotionActivity);
        }
    }

    public R<Object> createActivityByPython(ErpSellerStorePromotionActivity activity) {
//        ErpSellerStorePromotionActivity activity = erpSellerStorePromotionActivityMapper.selectById(activityId);
//        if (ObjectUtils.isNull(activity)){
//            return R.fail("活动不存在");
//        }

        //获取店铺
        ErpSellerStoreCookie cookie = erpSellerStoreCookieMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreCookie>().eq(ErpSellerStoreCookie::getStoreId,activity.getStoreId())
        );
        if (ObjectUtils.isNull(cookie)){
            return R.fail("获取cookie失败");
        }
        JSONObject object = new JSONObject();
        object.put("cookie_str",cookie.getCookie());
        //开始时间转时间戳
        String startTime = activity.getStartTime();
        String endTime = activity.getEndTime();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化当前时间


        LocalDateTime startTimeDT = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime endTimeDT = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 将 LocalDateTime 对象转换为 Instant 对象，该对象表示一个确切的时间点
//        Instant endTimeIT = endTimeDT.atZone(ZoneId.systemDefault()).toInstant();
//        Instant startTimeIT = startTimeDT.atZone(ZoneId.systemDefault()).toInstant();
//        long endTimestamp = endTimeIT.toEpochMilli();
//        long startTimestamp = startTimeIT.toEpochMilli();
        Long endTimestamp = endTimeDT.toEpochSecond(ZoneOffset.UTC);
        Long startTimestamp = startTimeDT.toEpochSecond(ZoneOffset.UTC);

        String endStr = endTimestamp.toString() + "000";
        String startStr = startTimestamp.toString() + "000";

        object.put("activityName",activity.getPromotionName());
        object.put("activityStartTime",startStr);
        object.put("activityEndTime",endStr);


        String body = getReturnBody(object.toJSONString());

        System.out.println(body);
        JSONObject bodyJson = JSONObject.parseObject(body);
        Integer code = bodyJson.getInteger("code");
        if (code != 200) {
            return R.ok("失败");
        }else {
            return R.ok("设置成功");
        }
    }

    private String getReturnBody(String data) {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://47.94.131.193:8000/activity/create");
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Encoding", "gzip");
        post.setEntity(new StringEntity(data, StandardCharsets.UTF_8));
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpEntity response = httpResponse.getEntity();
        try {
            return EntityUtils.toString(response,StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
